package com.sun.sviewhelper.base;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewbinding.ViewBinding;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;

public abstract class BaseAdapter<T, VM extends ViewBinding> extends RecyclerView.Adapter<BaseAdapter.BaseViewHolder<VM>> {
    protected Context context;
    protected LayoutInflater inflater;
    private List<T> datas;
    private OnItemClickListener onItemClickListener;

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public BaseAdapter(Context context) {
        this.context = context;
        datas = new ArrayList<>();
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public List<T> getDataList(){
        return datas;
    }

    public void setDataList(List<T> list){
        datas.clear();
        datas.addAll(list);
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public BaseViewHolder<VM> onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new BaseViewHolder<VM>(getBinding(parent));
    }

    @Override
    public void onBindViewHolder(@NonNull BaseViewHolder<VM> holder, int position) {
        onBeforeBind(holder, position);
        holder.itemBinding.getRoot().setOnClickListener(v -> {
            if (onItemClickListener != null) onItemClickListener.onItemClick(v, position);
        });
    }

    protected abstract void onBeforeBind(BaseViewHolder<VM> holder, int position);

    @Override
    public int getItemCount() {
        return datas.size();
    }

    private VM getBinding(ViewGroup parent) {
        ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
        Class cls = (Class) type.getActualTypeArguments()[1];
        try {
            Method method = cls.getDeclaredMethod("inflate", LayoutInflater.class, ViewGroup.class, boolean.class);
            return (VM) method.invoke(null, inflater, parent, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public interface OnItemClickListener {
        void onItemClick(View view, int position);
    }


    public static class BaseViewHolder<VM extends ViewBinding> extends RecyclerView.ViewHolder {
        private VM itemBinding;

        public BaseViewHolder(@NonNull VM binding) {
            super(binding.getRoot());
            this.itemBinding = binding;
        }

        public VM getItemBinding() {
            return itemBinding;
        }

    }
}
